<template>
   <Suspense>
      <template #default>
         <VantaBackground></VantaBackground>
      </template>
   </Suspense>
   <div class="intrProduct" ref="typedText"></div>
   <div class="login-form" style="max-height: 425px;">
      <h2 style="margin-top: 10px;">登录</h2>
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick" stretch="true">
         <el-tab-pane label="扫码登录" name="first">
            <wxlogin v-if="appid && redirect_uri" :appid="appid" scope="snsapi_login" :redirect_uri="redirect_uri"
               :href="href" :state="state"></wxlogin>
         </el-tab-pane>
         <el-tab-pane label="手机号登录" name="second">
            <el-form :model="loginParams" ref="refForm" :rules="rules">
               <el-form-item label="手机号" prop="phone" label-width="68px" style="margin-right: 25px; margin-top: 20px;">
                  <el-input v-model="loginParams.phone" placeholder="请输入手机号" clearable
                     @keyup.enter.native="handleLogin" />
               </el-form-item>
               <el-form-item label="密码" prop="password" label-width="68px" style="margin-right: 25px;">
                  <el-input v-model="loginParams.password" type="password" show-password placeholder="请输入密码" clearable
                     @keyup.enter.native="handleLogin(refForm)" />
               </el-form-item>
               <el-button type="primary" icon="el-icon-search" size="default" @click="handleLogin(refForm)"
                  style="margin-right: 5px; margin-left: 5px;">登录</el-button>
            </el-form>
         </el-tab-pane>
      </el-tabs>

   </div>
   <p class="footer">&copy; @2024 乐集网所有Copyright <a href="https://beian.miit.gov.cn/" target="_blank">苏ICP备2023028462号</a></p>
</template>

<script lang="ts" setup>
import { defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { showErrorMsg } from '@/api/common';
// import VantaBackground from "@/views/background/VantaBackground.vue"
const VantaBackground = defineAsyncComponent(() => import('@/views/background/VantaBackground.vue'))
import { useRouter } from 'vue-router';
import type { FormInstance, FormRules } from 'element-plus'
import { setToken, setMenuList } from '@/utils/auth'
import { wxRender, normalLogin } from '@/api/user/user';
import wxlogin from 'vue-next-wxlogin';
import type { TabsPaneContext } from 'element-plus';
import Typed from 'typed.js';
import type { ApiResponse } from '@/api/common';
import type { LoginParams, UserInfoResponse, AppIdRedirectUrl } from '@/api/user/user';
const router = useRouter();
const appid = ref<string>('');
const redirect_uri = ref<string>('');
const state = ref<string>('');
// 自定义样式链接
const href = ref<string>('data:text/css;base64,LmltcG93ZXJCb3ggLnFyY29kZSB7d2lkdGg6IDIwMHB4OyBoZWlnaHQ6MjAwcHg7fQouaW1wb3dlckJveCAudGl0bGUge2Rpc3BsYXk6IG5vbmU7fQouaW1wb3dlckJveCAuaW5mbyB7d2lkdGg6IDIwMHB4O30KLnN0YXR1c19pY29uIHtkaXNwbGF5OiBub25lfQouaW1wb3dlckJveCAuc3RhdHVzIHt0ZXh0LWFsaWduOiBjZW50ZXI7fSA=');
const typedText = ref<HTMLElement | null>(null);
let loginParams: LoginParams = reactive({
   phone: '',
   password: '',
})
let rules = reactive<FormRules<LoginParams>>({
   phone: [{
      required: true,
      message: '请输入手机号',
      trigger: 'change'
   }],
   password: [{
      required: true,
      message: '请输入密码',
      trigger: 'change'
   }],
})
const activeName = ref('first')
const handleClick = (tab: TabsPaneContext, event: Event) => {
   if (tab.paneName == 'first') {
      wxLogin();
      // beginIntervalGetLoginStatus();
   } else {
      // clearInterval(intervalTaskId.value);
   }
}
const refForm = ref<FormInstance>()
const handleLogin = async (formEl: FormInstance | undefined) => {
   if (!formEl) return
   await formEl.validate((valid, fields) => {
      if (valid) {
         normalLogin(loginParams).then((res: ApiResponse<UserInfoResponse>) => {
            if (res.status != 200) {
               showErrorMsg(res.msg);
            } else {
               setToken(res.data.token);
               setMenuList(res.data.menuList)
               // userStore.login(); // 确保这行代码正确更新了登录状态
               router.push({ name: 'Index' });
            }
         });
      } else {
         console.log('error submit!', fields)
      }
   })
}
const wxLogin = () => {
   wxRender().then((res: ApiResponse<AppIdRedirectUrl>) => {
      if (res.status != 200) {
         showErrorMsg(res.msg);
      } else {
         const appIdRedirectUrl = res.data;
         if (appIdRedirectUrl) {
            // url.value = redirectUrl;
            // window.location.href = redirectUrl;
            appid.value = appIdRedirectUrl.wxClientId;
            redirect_uri.value = appIdRedirectUrl.redirectUrl;
            state.value = appIdRedirectUrl.state;
         }
      }
   })
}
onMounted(() => {
   if (typedText.value) {
      new Typed(typedText.value, {
         strings: ["欢迎来到乐集网！", "网站目前开放", "工具类、家庭相册、周影院等功能", "微信扫码登录，开始你的旅程吧！"],
         typeSpeed: 90,
         backSpeed: 20,
         loop: true
      });
   }
   wxLogin();
})
</script>

<style scoped>
.intrProduct {
   position: fixed;
   top: 35%;
   left: 30%;
   /* width: 300px; */
   background-color: rgba(255, 255, 255, 0.8);
   padding: 15px;
   border-radius: 10px;
   text-align: center;
   /* Courier New ；  Trebuchet MS*/
   /* font-family: Verdana; */
   /* font-family:Times, serif; */
   font-size: 20px;
}

.login-form {
   position: fixed;
   top: 20%;
   right: 20%;
   width: 300px;
   /*transform: translate(50%, -70%);*/
   background-color: rgba(255, 255, 255, 0.8);
   padding: 5px;
   border-radius: 10px;
   text-align: center;
}

.login-form h2 {
   margin-bottom: 20px;
}

.login-form input {
   width: 60%;
   padding: 10px;
   margin-bottom: 10px;
}

.login-form button {
   width: 60%;
   padding: 10px;
   background-color: #007bff;
   color: #fff;
   border: none;
   border-radius: 5px;
   cursor: pointer;
   margin-top: 15px;
   margin-bottom: 20px;
}
.footer {
   position: fixed;
   bottom: 2%;
   margin-left: 35%;
}
</style>